package com.mdd.front.config.wxpay;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.mdd.common.entity.system.SystemConfig;
import com.mdd.common.mapper.system.SystemConfigMapper;
import com.mdd.front.service.system.ISystemDevPayService;
import com.mdd.front.vo.system.SystemDevWxPayConfig;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author panweiliang
 */
@Configuration
@ConditionalOnClass(WxPayService.class)
@AllArgsConstructor
public class WxMpConfiguration {

  @Resource
  private SystemConfigMapper systemConfigMapper;

  @Bean
  @ConditionalOnMissingBean
  public WxMpService wxMpService() {
      Map<String, String> map = getDbConfig();
      WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
      config.setAppId(map.getOrDefault("appId", "")); // 设置微信公众号的appid
      config.setSecret(map.getOrDefault("appSecret", "")); // 设置微信公众号的app corpSecret
      config.setToken(map.getOrDefault("token", "")); // 设置微信公众号的token
      config.setAesKey(map.getOrDefault("encodingAesKey", "")); // 设置微信公众号的EncodingAESKey
      WxMpService wxService = new WxMpServiceImpl();// 实际项目中请注意要保持单例，不要在每次请求时构造实例，具体可以参考demo项目
      wxService.setWxMpConfigStorage(config);
      return wxService;
  }

  private Map<String, String> getDbConfig() {
    List<SystemConfig> configs = systemConfigMapper.selectList(
            new QueryWrapper<SystemConfig>()
                    .select("id", "type", "name", "value")
                    .eq("type", "oa_channel"));

    Map<String, String> map = new LinkedHashMap<>();
    for (SystemConfig config : configs) {
      map.put(config.getName(), config.getValue());
    }
    return map;
  }

}
